<template>
  <div class="page-container page-container-create">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>会员中心</el-breadcrumb-item>
        <el-breadcrumb-item>折扣卡管理</el-breadcrumb-item>
        <el-breadcrumb-item>扣卡列表</el-breadcrumb-item>
        <el-breadcrumb-item>查看折扣卡</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div>
      <div class="disCountDetail mb40">
        <p class="common-style t_l w100 mb30">
          <span class="label font14 color333">折扣卡名称：</span>
          <span class="value font14 color333">{{discountThemeData.discountThemeName}}</span>
        </p>
        <p class="common-style t_l w100 mb30">
          <span class="label font14 color333 turnInlineBlock w84 t_r">折扣：</span>
          <span class="value font14 color333">{{discountThemeData.discountValue}}折</span>
        </p>
        <p class="common-style t_l w100 mb30">
          <span class="label font14 color333 turnInlineBlock w84 t_r">有效期：</span>
          <span class="value font14 color333">{{discountThemeData.startTime}}至{{discountThemeData.endTime}}</span>
        </p>
        <p class="common-style t_l w100 mb30">
          <span class="label font14 color333 turnInlineBlock w84 t_r">使用渠道：</span>
          <span class="value font14 color333">{{getChannelNames()}}</span>
        </p>
      </div>


      <div class="tab-container">
        <el-tabs v-model="discountCardTabStatus"  type="border-card" @tab-click="refreshCardTab()" >
          <el-tab-pane :label="noBindingDiscountCardLabel" name="1">
          <div class="row-line-button t_r">
            <div class="mb30">
              <el-button class="searchButton" size="mini" @click="refreshCardTab">刷新</el-button>
              <el-button class="searchButton" size="mini" @click="batchBindingDiscountCardDialog(1)" v-if="discountThemeData.deptId == deptId">批量绑定</el-button>
            </div>
          </div>

          <el-table
            :data="noBindingDiscountCardData"
            v-loading="noBindingLoading"
            style="width: 100%"
          >
              <el-table-column prop="discountCardCode" label="卡号" sortable align="center"></el-table-column>

              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    class="textButton"
                    @click="bindingDiscountCard(scope.row)"
                    :disabled="discountThemeData.deptId != deptId"
                  >绑定</el-button>
                </template>
              </el-table-column>
          </el-table>
          <!--分页栏-->
          <div class="toolbar t_r" v-if="noBindingDiscountCardData.length > 0">
            <el-pagination
              @size-change="handleSizeChangeNoBindingDiscountCardData"
              @current-change="handleCurrentChangeNoBindingDiscountCardData"
              :current-page="noBindingDiscountCardForm.start"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="noBindingDiscountCardForm.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="noBindingDiscountCardDataTotal"
            ></el-pagination>
          </div>
          </el-tab-pane>

          <el-tab-pane :label="bindingDiscountCardLabel" name="2">
          <div class="row-line-button t_r">
            <div class="mb30 oh">

               <el-button class="searchButton f_r" size="mini" @click="batchBindingDiscountCardDialog(2)" v-if="discountThemeData.deptId == deptId">批量解除绑定</el-button>
              <el-button class="searchButton f_r mr20" size="mini"  @click="searchFlag = !searchFlag" icon="el-icon-search">搜索</el-button>
              <el-form
                :inline="true"
                :model="bindingDiscountCardForm"
                size="mini"
                ref="bindingDiscountCardForm"
                class="rightForm f_r"
                :rules="bindingDiscountCardFormRules"
                v-if="searchFlag"
              >
                <el-form-item label="卡号：" prop="discountCardCode" class="mr30">
                  <el-input v-model="bindingDiscountCardForm.discountCardCode" clearable placeholder="输入卡号" maxlength="80" @input="changeInput($event)"></el-input>
                </el-form-item>
                <el-form-item label="用户账号：" prop="userAccount" class="mr30">
                  <el-input v-model="bindingDiscountCardForm.userAccount" clearable placeholder="输入用户账号" maxlength="80" @input="changeInput($event)"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称：" prop="nickName">
                  <el-input v-model="bindingDiscountCardForm.nickName" clearable placeholder="输入用户昵称" maxlength="80" @input="changeInput($event)"></el-input>
                </el-form-item>
                <el-form-item >
                  <el-button class="resetButton" size="mini" @click="queryBindingDiscountCards()">查询</el-button>
                  <el-button class="resetButton" plain size="mini" @click="resetBindingDiscountCardSearch()">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>

          <!-- <el-row> -->

          <!-- </el-row> -->

          <el-table
            :data="bindingDiscountCardData"
            style="width: 100%"
            v-loading="bindingLoading"
          >
            <el-table-column prop="discountCardCode" label="卡号" sortable align="center"></el-table-column>
            <el-table-column prop="userAccount" label="用户账号" sortable align="center" >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  class="textButton"
                  @click="memberUserDeatail(scope.row)"
                  :disabled="discountThemeData.deptId != deptId"
                >{{scope.row.userAccount}}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="nickName" label="用户昵称" sortable align="center"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  class="textButton"
                  @click="untieDiscountCardClick(scope.row)"
                  :disabled="discountThemeData.deptId != deptId"
                >解除绑定</el-button>
              </template>
            </el-table-column>

          </el-table>
          <!--分页栏-->
          <div class="toolbar t_r" v-if="bindingDiscountCardData.length > 0">
            <el-pagination
              @size-change="handleSizeChangeBindingDiscountCardData"
              @current-change="handleCurrentChangeBindingDiscountCardData"
              :current-page="bindingDiscountCardForm.start"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="bindingDiscountCardForm.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="bindingDiscountCardDataTotal"
            ></el-pagination>
          </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>


    <!-- 绑定折扣卡 -->
    <el-dialog :visible.sync="bindingDiscountCardVisible" title="绑定折扣卡" :close-on-click-modal="false">
      <div>
        <div>
          <el-form inline :model="userForm" ref="userForm" :size="size" :rules="userFormRules">
            <div class="col-sm-9">
              <el-form-item label="用户账号：" prop="userAccount" class="w178 mb30" >
                <el-input v-model="userForm.userAccount" auto-complete="off" clearable  placeholder="输入用户账号" maxlength="80" @input="changeInput($event)"></el-input>
              </el-form-item>
              <el-form-item label="用户昵称：" prop="nickName" class="w178" >
                <el-input v-model="userForm.nickName" auto-complete="off" clearable  placeholder="输入用户昵称" maxlength="80" @input="changeInput($event)"></el-input>
              </el-form-item>
              <el-form-item label="用户手机号：" prop="phone" class="w178" >
                <el-input v-model="userForm.phone" auto-complete="off" clearable  placeholder="输入用户手机号" maxlength="11" oninput="value=value.replace( /[^\d]/g,'')" @input="changeInput($event)"></el-input>
              </el-form-item>
            </div>
          </el-form>

          <el-row class="mb30 mt20 t_r">
            <el-button class="resetButton" size="mini" @click="resetUserForm()" icon="el-icon-refresh">重置</el-button>
            <el-button class="searchButton" size="mini" @click="userFormFind()" icon="el-icon-search">搜索</el-button>
          </el-row>
        </div>
        <div>
          <el-table
            :data="userTableData"
            :header-cell-style="tableHeaderColor"
            ref="multipleTable"
            style="width: 100%"
            v-loading="userTableDataLoading"
            size="mini"
          >
            <el-table-column prop="userAccount" label="用户账号" align="center"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" align="center"></el-table-column>
            <el-table-column prop="phone" label="用户手机号" align="center"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button type="text" v-if="scope.row.id != bindingForm.memberUserId" @click.native="selectMember(scope.row)">选择</el-button>
                <el-button type="text"  v-else-if="scope.row.id == bindingForm.memberUserId" disabled>已选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button class="cancelButton" plain size="mini" @click.native="bindingDiscountCardVisible = false">取消</el-button>
        <el-button
          size="mini"
          class="searchButton"
          @click="bindingDiscountCardClick"
          :loading="false"
        >确定绑定</el-button>
      </div>
    </el-dialog>

    <!-- 批量绑定折扣卡 -->
    <el-dialog :visible.sync="batchBindingDiscountCardVisible" :title="batchUserForm.actionType == 2 ? '批量解除绑定折扣卡' : '批量绑定折扣卡'" :close-on-click-modal="false">
      <div>
        <div>
          <el-form :model="batchUserForm" ref="batchUserForm" class="mb60">
            <el-row class="labelAlignment mb30">
              <el-form-item label="新老用户：" prop="userTypes" class="w178">
                <div class="flex">
                  <el-checkbox :indeterminate="isIndeterminateUserType" v-model="checkAllUserType" class="mr45" @change="handleCheckAllChangeUserType">
                  <span class="turnInlineBlock w50 t_l">  全部</span>
                  </el-checkbox>
                  <el-checkbox-group v-model="batchUserForm.userTypes" @change="handleCheckedUserTypesChange">
                    <el-checkbox v-for="item in userTypes" :label="item.code" :key="item.code" class="mr45">
                    <span class="turnInlineBlock w50 t_l">{{item.name}}</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-row> 
            <el-row class="labelAlignment mb30">
              <el-form-item label="会员类型：" prop="memberTypes" class="w178">
                <div class="flex">
                  <el-checkbox class="mr45" :indeterminate="isIndeterminateMemberType" v-model="checkAllMemberType" @change="handleCheckAllChangeMemberType">
                    <span class="turnInlineBlock w50 t_l">全部</span>

                    </el-checkbox>
                  <el-checkbox-group v-model="batchUserForm.memberTypes" @change="handleCheckedMemberTypesChange">
                    <el-checkbox v-for="item in memberTypes" :label="item.code" :key="item.code" class="mr45">
                    <span class="turnInlineBlock w50 t_l">  {{item.name}}</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-row>
            <el-form-item  prop="memberGradeList" >
              <div class="mb20">
                    <span class="color333 font16">会员等级：</span>
                  </div>
              <div v-for="(memberGrade,index) in memberGradeList" :key="memberGrade.deptId" class="flexBox pdl15 oh">
                <div class="child-name">
                <span class="turnInlineBlock w126 oe t_r">  {{memberGrade.childName}}</span>：
                </div>
                <div class="checkboxes">
                  <el-checkbox class="mr45" :indeterminate="memberGrade.isIndeterminate" v-model="memberGrade.checkAll" @change="handleMemLevelCheckAllChange(index,memberGrade.checkAll)">全选</el-checkbox>
                  <el-checkbox-group v-model="memberGrade.levelSelectList" >
                    <el-checkbox class="mb20 mr45" @change="memLevelChange(index,memberGrade.levelList)" v-for="level in memberGrade.levelList" :checked="level.checked" v-model="level.id" :label="level.id" :key="level.key">
                    <span class="turnInlineBlock w104 ">  {{level.levelName.length >= 6 ? level.levelName.slice(0,5)+"..." : level.levelName}}</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-form-item>
          </el-form>
          <el-row class="w100 t_c">
            <el-button class="cancelButton mr60" size="mini" @click="batchBindingDiscountCardVisible = false" >取消</el-button>
            <el-button class="searchButton" size="mini" @click="batchBindingOrUntie()">{{batchUserForm.actionType == 1 ? '确定绑定':'确定解除绑定'}}</el-button>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import cardRequest from "@/discountCard/request/cardRequest";
  export default {
    name: "discountCardBinding",
    components: {},
    computed: {
      mainTabs: {
        get() {
          return this.$store.state.tab.mainTabs;
        },
        set(val) {
          this.$store.commit("updateMainTabs", val);
        }
      },
      mainTabsActiveName: {
        get() {
          return this.$store.state.tab.mainTabsActiveName;
        },
        set(val) {
          this.$store.commit("updateMainTabsActiveName", val);
        }
      }
    },
    data() {


      return {
        noBindingLoading: false,
        bindingLoading: false,
        userTableDataLoading: false,
        //绑定操作表单
        bindingForm:{
          id: null,
          memberUserId: null,
          thirdUserId: null,
          actionType: 1,
        },
        //绑定操作表单
        untieForm:{
          id: null,
          actionType: 2,
        },

        size:'mini',
        id: this.$route.params.id,
        deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
        deptId: localStorage.getItem("deptId"), //当前登录用户所属组织类型
        //form
        discountThemeData: {
        },
        //渠道Tree List
        channelList: [{ childName: "卡奥斯运营中心", id: "179",deptId: '179'}],
        discountCardTabStatus: '1',//未绑定

        //未绑定
        noBindingDiscountCardLabel: '未绑定(0)',
        noBindingDiscountCardData:[],
        noBindingDiscountCardForm:{
          start: 1,
          limit: 10,
          status: 1,
        },
        noBindingDiscountCardDataTotal: 0,

        //已绑定
        bindingDiscountCardLabel: '已绑定(0)',
        bindingDiscountCardData:[

        ],
        bindingDiscountCardForm:{
          discountCardCode: null,
          userAccount: null,
          nickName: null,
          status: 2,
          start: 1,
          limit: 10,
        },
        bindingDiscountCardDataTotal: 0,

        searchFlag:false,
        bindingDiscountCardFormRules: {

        },

        //绑定折扣卡
        bindingDiscountCardVisible: false,
        userForm:{
          nickName: null,
          userAccount: null,
          phone: null,
        },
        userFormRules: {
        },
        userTableData:[],

        //批量绑定折扣卡
        batchBindingDiscountCardVisible: false,
        batchUserForm:{
          userTypes: [1,2],
          memberTypes: [1,2],
          levelCodes: [],
          memberLevel: [],
          actionType: 1,
        },

        checkAllUserType: true,
        checkAllMemberType: true,
        isIndeterminateUserType: false,
        isIndeterminateMemberType: false,
        userTypes: [{code:1, name:'新用户'},{code:2, name:'老用户'}],
        memberTypes: [{code:1, name:'普通会员'},{code:2, name:'VIP会员'}],
        userTypeKeys: [1, 2],
        memberTypeKeys: [1, 2],

        isIndeterminateMemberLevel: false,
        memberLevels: [],
        memberLevelKeys: [1, 2],

        //会员等级
        memberGradeList: [],
      };
    },

    methods: {

      queryBindingDiscountCards(){
        this.bindingDiscountCardForm.start = 1;
        this.bindingDiscountCardForm.limit = 10;
        this.queryBindingDiscountCardList();
      },

      //输入框无法输入问题
      changeInput(val) {
        this.$forceUpdate();
      },


      getChannelNames(){
        let channelNames = [];
        if(this.discountThemeData.channelCodes!=undefined){
          let channels = this.discountThemeData.channelCodes.split(',');
          if (this.discountThemeData.deptId == 179) {
            if(channels.indexOf('179') == -1){
              channels.unshift('179');
            }
          }
          channels.forEach(item=>{
            let channelName = this.getChannelName(item);
            if(channelName != ""){
              channelNames.push(channelName);
            }
          });
        }
       return  channelNames.join(" | ");
      },

      memberUserDeatail(row){
        this.$router.push({path: "/UserInfo/" + row.memberUserId + "/" + row.thirdUserId + "/" + 1});
      },

      getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
      },

      //批量绑定或者解绑用户
      batchBindingOrUntie(){
        let this_ = this;
        let memberQuerys = [];
        //this.memberGradeList.levelSelectList
        let selectLevleIds = [];
        this.memberGradeList.forEach(item=>{
          if(item.levelSelectList && item.levelSelectList.length > 0){
            selectLevleIds.push(item.levelSelectList);
          }
        });
        //校验参数  新老用户，会员类型，会员等级，三选一
        if(this.batchUserForm.userTypes.length == 0 && this.batchUserForm.memberTypes.length == 0 && selectLevleIds.length == 0){
          this.$message({ message: "新老用户，会员类型，会员等级条件请最少设置其中一项", type: "error" });
          return;
        }

        let channels = this.discountThemeData.channelCodes.split(',');
        if (this.deptType == 0) {
          if(channels.indexOf('179') == -1){
            channels.unshift('179');
          }
        }
        for (var i = 0; i < channels.length; i++) {
          let item = this.channelList.find(function (item, index) {
            return item.id === channels[i];
          });

          if(typeof(item)!="undefined"){
            let memberQuery = {};
            memberQuery.deptId = item.deptId;
            if(this.batchUserForm.userTypes.length > 0){
              memberQuery.userTypes = this.batchUserForm.userTypes;
            }
            if(this.batchUserForm.memberTypes.length > 0){
              memberQuery.memberTypes = this.batchUserForm.memberTypes;
            }
            let itemGrade = this.memberGradeList.find(function (itemGrade, index) {
              return itemGrade.businessId === item.id;
            });
            if(typeof(itemGrade)!="undefined"){
              memberQuery.memberGradeIds = itemGrade.levelSelectList;
            }
            memberQuerys.push(memberQuery);
          }
        }

        let callback = function(res) {
          if(res.code == '0000'){
            this_.queryBindingOrNoCount();
            this_.queryNoBindingDiscountCardList();
            this_.queryBindingDiscountCardList();
          }else {
            this_.$confirm(msg, res.msg, {
              type: "warning",
              dangerouslyUseHTMLString: true,
              closeOnClickModal: false,
            }).then(() => {

            }).catch(() => {

            });
          }
        };
        let param = {discountThemeId: this.id, actionType: this.batchUserForm.actionType,memberQuerys:memberQuerys};
        cardRequest.batchBindingOrUntieDiscountCard(param, callback);

        let msg = this.batchUserForm.actionType == 1 ? '批量绑定需要若干分钟，查看请刷新页面' : '批量解绑需要若干分钟，查看请刷新页面';
        this.batchBindingDiscountCardVisible = false;
        this.$confirm(msg, "提示", {
          type: "warning",
          dangerouslyUseHTMLString: true,
          closeOnClickModal: false,
        }).then(() => {

        }).catch(() => {

        });

      },

      //批量绑定弹框
      batchBindingDiscountCardDialog(actionType){
        this.batchBindingDiscountCardVisible = true;
        this.batchUserForm.actionType = actionType;
        //请求 会员等级，会员等级接口
        this.getMemberGradeList();
        this.resetForm('batchUserForm');
        this.checkAllUserType = true;
        this.checkAllMemberType = true;
        this.isIndeterminateUserType = false;
        this.isIndeterminateMemberType = false;
      },

      //获取会员等级
      getMemberGradeList(){
        let deptNodeList = [];
        let this_ = this;
        let deptIds = [];

        deptIds.push(this.deptId);
        let userInfo = JSON.parse(localStorage.getItem("user"));
        deptNodeList.push({deptId:userInfo.deptId,"childName":userInfo.deptName,"id":userInfo.businessId})

        let callback = function(res) {
          if(res.code == '0000'){
            let levelList = res.data;
            //遍历
            this_.memberGradeList = [];
            deptNodeList.forEach(deptInfo=>{
              let levelInfo = levelList.find(function(level) {
                return level.deptId === deptInfo.deptId;
              })
              if(levelInfo == undefined){
                //没有数据不展示
                //this_.memberGradeList.push({ childName: deptInfo.childName, businessId: deptInfo.id ,checkAll: true, isIndeterminate: false,  levelSelectList: [], levelList:[]})
              }else{
                //添加数据
                let selectLevelIds = levelInfo.mememberGradeResponseList.map((item,index) =>{
                  return item.id;
                })
                levelInfo.mememberGradeResponseList.forEach(item=>{
                  item.key = this_.getUuid();
                })
                this_.memberGradeList.push({ childName: deptInfo.childName, businessId: deptInfo.id ,  levelSelectList: selectLevelIds,  checkAll: true , isIndeterminate: false , levelList:levelInfo.mememberGradeResponseList})
              }
            })
          }else{
            this_.memberGradeList = [];
          }
        };
        this.utils.request.listMemberGradeForMarket({"deptIds": deptIds.join(",")},callback)
      },

      //会员等级
      handleMemLevelCheckAllChange(index,checked){
        if(!checked){
          //取消全部
          let memberSelectGrade = this.memberGradeList[index];
          memberSelectGrade.checkAll = false;
          memberSelectGrade.isIndeterminate = false;
          memberSelectGrade.levelSelectList = [];
          // this.$s
          this.$set(this.memberGradeList,index,memberSelectGrade);

        }else{
          //选中全部
          let ids = [];
          this.memberGradeList[index].levelList.forEach(item=>{
            ids.push(item.id)
          })
          let memberSelectGrade = this.memberGradeList[index];
          memberSelectGrade.checkAll = true;
          memberSelectGrade.isIndeterminate = false;
          memberSelectGrade.levelSelectList = ids;
          // this.$s
          this.$set(this.memberGradeList,index,memberSelectGrade);
        }
      },

      memLevelChange(index, levelList){
        //查看当前子平台是否全选
        let levelSelectList = this.memberGradeList[index].levelSelectList;
        if(levelSelectList == null || levelSelectList.length < 1){
          //没有选中子级
          let memberSelectGrade = this.memberGradeList[index];
          memberSelectGrade.checkAll = false;
          memberSelectGrade.isIndeterminate = false;
          memberSelectGrade.levelSelectList = [];
          // this.$s
          this.$set(this.memberGradeList,index,memberSelectGrade);
          return;
        }
        let noSelectIds = [];
        levelList.forEach(item=>{
          if(levelSelectList.indexOf(item.id) == -1){
            //存在
            noSelectIds.push(item.id);
          }
        })
        if(noSelectIds.length < 1){
          //全选
          let ids = [];
          this.memberGradeList[index].levelList.forEach(item=>{
            ids.push(item.id)
          })
          let memberSelectGrade = this.memberGradeList[index];
          memberSelectGrade.checkAll = true;
          memberSelectGrade.isIndeterminate = false;
          memberSelectGrade.levelSelectList = ids;
          this.$set(this.memberGradeList,index,memberSelectGrade);
        }else{
          //没有全选
          let ids = [];
          let memberSelectGrade = this.memberGradeList[index];
          memberSelectGrade.checkAll = false;
          memberSelectGrade.isIndeterminate = true;
          this.$set(this.memberGradeList,index,memberSelectGrade);
        }
      },

      //切换tap
      refreshCardTab(){
        this.queryBindingOrNoCount();
        this.queryNoBindingDiscountCardList();
        this.queryBindingDiscountCardList();
      },


      //查询绑定和未绑定总数
      queryBindingOrNoCount(){
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.noBindingDiscountCardLabel = '未绑定' + '(' + res.data.noBindingTotal + ')';
            this_.bindingDiscountCardLabel = '已绑定' + '(' + res.data.bindingTotal + ')';
          }
        };
        cardRequest.queryBindingOrNoCount({discountThemeId: this.id}, callback)
      },

      //查询未绑定折扣卡列表
      queryNoBindingDiscountCardList(){
        let this_ = this;
        this.noBindingLoading = true;
        let callback = function(res) {
          if (res.code == "0000") {
            if(res.data.total != 0){
              this_.noBindingDiscountCardData = res.data.rows;
            }else{
              this_.noBindingDiscountCardData = [];
            }
            this_.noBindingDiscountCardDataTotal = res.data.total;
          }
          this_.$nextTick(()=>{
            this_.noBindingLoading = false;
          })
        };
        this.noBindingDiscountCardForm.discountThemeId = this.id;
        cardRequest.queryDiscountCardList(this.noBindingDiscountCardForm, callback)
      },

      //查询绑定折扣卡列表
      queryBindingDiscountCardList(){
        let this_ = this;
        this.bindingLoading = true;
        let callback = function(res) {
          if (res.code == "0000") {
            if(res.data.total != 0){
              this_.bindingDiscountCardData = res.data.rows;
            }else{
              this_.bindingDiscountCardData = [];
            }
            this_.bindingDiscountCardDataTotal = res.data.total;
          }
          this_.$nextTick(()=>{
            this_.bindingLoading = false;
          })
        };
        this.bindingDiscountCardForm.discountThemeId = this.id;
        cardRequest.queryDiscountCardList(this.bindingDiscountCardForm, callback)
      },

      //新老用户全选 赋值控制全选或清除
      handleCheckAllChangeUserType(val) {
        this.batchUserForm.userTypes = val ?  this.userTypeKeys : [];
        this.isIndeterminateUserType = false;
      },
      //新老用户选择
      handleCheckedUserTypesChange(value) {
        let checkedCount = value.length;
        this.checkAllUserType = checkedCount === this.userTypes.length;
        this.isIndeterminateUserType = checkedCount > 0 && checkedCount < this.userTypes.length;
      },

      //会员类型全选 赋值控制全选或清除
      handleCheckAllChangeMemberType(val) {
        this.batchUserForm.memberTypes = val ?  this.memberTypeKeys : [];
        this.isIndeterminateMemberType = false;
      },
      //会员类型选择
      handleCheckedMemberTypesChange(value) {
        let checkedCount = value.length;
        this.checkAllMemberType = checkedCount === this.memberTypes.length;
        this.isIndeterminateMemberType = checkedCount > 0 && checkedCount < this.memberTypes.length;
      },


      tableHeaderColor({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return "background-color:rgb(250,250,250);";
        }
      },

      resetUserForm(){
        //需要校验的keys
        let keys = ["nickName","userAccount","phone"];
        //调用校验
        let  boo = this.seachTableUtils.checkFromIsNull(this.userForm,keys)
        if(!boo){
          return;
        }
        this.resetForm("userForm");
      },

      //查询会员用户
      userFormFind(){
        this.bindingForm.thirdUserId = null;
        this.bindingForm.memberUserId = null;

        if((this.userForm.nickName == null ||  this.userForm.nickName == '') && (this.userForm.userAccount == null ||  this.userForm.userAccount == '') && (this.userForm.phone == null ||  this.userForm.phone == '')){
          this.$message({message: "请输入查询条件", type: "warning"});
          return;
        }
        let this_ = this;
        this.userTableDataLoading = true;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.userTableData = res.data;
          }
          this_.$nextTick(()=>{
            this_.userTableDataLoading = false;
          });
        };

        cardRequest.listMemberUserInfo(this.userForm, callback);
      },

      /**
       * 选择绑定用户
       */
      selectMember(row){
        this.bindingForm.memberUserId = row.id;
        this.bindingForm.thirdUserId = row.thirdUserId;
      },

      //绑定折扣卡
      bindingDiscountCardClick(){
        if(this.bindingForm.memberUserId == null){
          this.$message({message: '请选择用户', type: "error"});
          return;
        }
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.$message({message: '绑定成功', type: "success"});
            this_.bindingDiscountCardVisible = false;
            //this_.resetBindingOrNoBindingFrom();
            this_.queryBindingOrNoCount();
            this_.queryNoBindingDiscountCardList();
            this_.queryBindingDiscountCardList();
          }
        };
        this.bindingForm.discountThemeId  = this.id;
        cardRequest.bindingOrUntieDiscountCard(this.bindingForm, callback);
      },

      bindingDiscountCard(row){
        this.bindingDiscountCardVisible = true;
        this.bindingForm.memberUserId = null;
        this.bindingForm.thirdUserId = null
        this.resetForm('userForm');
        this.userTableData = [];
        this.bindingForm.id = row.id;
      },

      getChannelName(code) {
        let item = this.channelList.find(function (item, index) {
          return item.id == code;
        })
        return typeof(item)=="undefined" ? "" : item.childName;
      },

      //解绑折扣卡
      untieDiscountCardClick(row){
        let this_ = this;
        this.$confirm('您确定要解除折扣卡与用户的绑定？', "提示", {
          type: "warning",
          dangerouslyUseHTMLString: true,
          closeOnClickModal: false,
        }).then(() => {
          let callback = function(res) {
            if (res.code == "0000") {
              this_.$message({message: '解除成功', type: "success"});
              this_.bindingDiscountCardVisible = false;
              this_.queryBindingOrNoCount();
              this_.queryNoBindingDiscountCardList();
              this_.queryBindingDiscountCardList();
            }else{
              this_.$confirm(res.msg, {
                type: "warning",
                dangerouslyUseHTMLString: true,
                closeOnClickModal: false,
              }).then(() => {

              }).catch(() => {

              });
            }
          };
          this_.untieForm.id = row.id;
          this_.untieForm.memberUserId = row.memberUserId;
          this_.bindingForm.discountThemeId  = this_.id;
          cardRequest.bindingOrUntieDiscountCard(this_.untieForm, callback);
        }).catch(() => {

        });
      },

      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
        }
      },

      resetBindingDiscountCardSearch(){
        //需要校验的keys
        let keys = ["discountCardCode","userAccount","nickName"]
        //调用校验
        let  boo = this.seachTableUtils.checkFromIsNull(this.bindingDiscountCardForm,keys)
        if(!boo){
          return;
        }
        this.resetForm("bindingDiscountCardForm");
        this.bindingDiscountCardForm.nickName = null;
        this.bindingDiscountCardForm.discountCardCode = null;
        this.bindingDiscountCardForm.userAccount = null;
        this.queryBindingDiscountCards();
      },

      handleSizeChangeNoBindingDiscountCardData(val) {
        this.noBindingDiscountCardForm.limit = val;
        this.noBindingDiscountCardForm.start = 1;
        this.queryBindingOrNoCount();
        this.queryNoBindingDiscountCardList();
      },

      handleCurrentChangeNoBindingDiscountCardData(pageNum) {
        this.noBindingDiscountCardForm.start = pageNum;
        this.queryBindingOrNoCount();
        this.queryNoBindingDiscountCardList();
      },

      handleSizeChangeBindingDiscountCardData(val) {
        this.bindingDiscountCardForm.limit = val;
        this.bindingDiscountCardForm.start = 1;
        this.queryBindingOrNoCount();
        this.queryBindingDiscountCardList();
      },

      handleCurrentChangeBindingDiscountCardData(pageNum) {
        this.bindingDiscountCardForm.start = pageNum;
        this.queryBindingOrNoCount();
        this.queryBindingDiscountCardList();
      },

      // tabs, 删除tab
      removeTabHandle(tabName) {
        this.mainTabs = this.mainTabs.filter(item => item.name !== tabName);
        if (this.mainTabs.length >= 1) {
          // 当前选中tab被删除
          if (tabName === this.mainTabsActiveName) {
            let tab = this.mainTabs[this.mainTabs.length - 1];
            this.$router.push(
              { path: tab.path,params: tab.params, query: tab.query},
              () => {
                this.mainTabsActiveName = this.$route.name;
              }
            );
          }
        } else {
          this.$router.push("/");
        }
      },


      // 点击取消返回用户旅程列表
      back() {
        this.removeTabHandle("查看折扣卡");
      },

      //获取旅程基本信息
      getDiscountThemeInfo(){
        let this_ = this;
        let callback = function(res) {
          if (res.code == "0000") {
            this_.discountThemeData =  res.data;
            this_.listMemberGradeForMarket();
          }
        };
        cardRequest.queryDiscountThemeInfo({id: this.id}, callback)
      },

      //获取子平台列表
      getChildList() {
        let this_ = this;
        this.utils.request.queryChildList({"deptIds": "179"}, res => {
          if (res.code == "0000" && res.data && res.data.length > 0) {
            res.data.forEach(item=>{
              this_.channelList.push(item);
            })
          }
        });
      },
      listMemberGradeForMarket(){
        let this_ = this;
        this_.memberLevels;
        cardRequest.listMemberGradeForMarket({}, res => {
          if (res.code == "0000" && res.data && res.data.length > 0) {
            this_.memberLevels = res.data;
          }
        });
      },

    },

    created(){
      this.getChildList();
    },

    mounted() {
      if (typeof this.$route.params.id != "undefined") {
        this.id = this.$route.params.id;
        this.getDiscountThemeInfo();
      }
      this.queryBindingOrNoCount();
      this.queryNoBindingDiscountCardList();
      this.queryBindingDiscountCardList();
    }
  };
</script>
<style lang="scss" scoped>
  .desc{
    color: #ffb100;
    font-size: 10px;
    margin-top: 10px;
  }

  .title {
    font-size: 16px;
    text-align: left;
  }
  .part {
    padding: 0 40px;
  }

  .mb50{
    margin-bottom: 50px;
  }
  .mt40{
    margin-top: 40px;
  }
  /deep/ .w410{
    width: 410px;
    .el-input__inner{
      width: 410px;
    }
  }
  .mb120{
    margin-bottom: 120px;
  }
  .w84{
    width: 84px;
  }
  .disCountDetail{
    padding: 30px;
    border: 1px solid #E7E7E7;
  }
  /deep/ .el-tabs--border-card>.el-tabs__content{
    padding: 0 !important;
  }
  .mr20{
    margin-right: 20px;
  }
  .flexBox{
  display: flex;
  flex-wrap: nowrap;
  align-content: flex-start;
  .child-name{
    flex-shrink: 0;
  }
  .checkboxes{
    display: flex;

  }

}
.pdl15{
  padding-left: 15px;
}
.w126{
  width: 126px;
}
.oe{
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.width100{
  width: 97px;
}
.w104{
  width: 104px;
}
.ml60{
  margin-left: 60px;
}
.pdl30{
  padding-left: 30px;
}
.pdt20{
  padding-top: 20px;
}
.w50{
  width:50px
}
</style>

